import { message } from "antd";
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router";
import { apiProfile } from "~/api";
import { useUserInfo } from "~/contexts/user-info";
import { getToken } from "~/utils/auth";

interface Props {
  children?: React.ReactNode;
}

export default function AuthCheck(props: Props) {
  const navigate = useNavigate();
  const location = useLocation();
  const [authChecked, setAuthChecked] = useState(false);
  const { setUserInfo } = useUserInfo(); // 获取更新用户信息的方法

  const _checkAuth = async () => {
    const token = getToken();
    if (!token) {
      // token 不存在，并且路由不在白名单里面，重定向到登录页
      setAuthChecked(true);
      navigate("/login", { replace: true });
      return;
    }

    try {
      const resp = await apiProfile();
      message.info("已登录");
      setUserInfo(resp);
      if (location.pathname.includes("login") && resp.permissions.length > 0) {
        navigate(resp.permissions[0]?.children?.[0]?.path || "/404", {
          replace: true,
        });
      }
    } catch (error) {
      navigate("/login", { replace: true });
    } finally {
      setAuthChecked(true);
    }
  };

  useEffect(() => {
    _checkAuth();
  }, []);

  if (!authChecked && location.pathname.includes("/login")) {
    return <div>加载中...</div>; // 或者使用一个加载动画组件
  }
  return props.children;
}
